package com.weifly.weistock.core.market.impl;

import com.weifly.weistock.core.market.StockKLineService;
import com.weifly.weistock.core.market.StockMarketConverter;
import com.weifly.weistock.core.market.StockPriceDto;
import com.weifly.weistock.core.market.bo.StockDayBO;
import com.weifly.weistock.core.market.bo.StockKLineBO;
import com.weifly.weistock.core.util.DateUtils;
import com.weifly.weistock.core.util.HttpRequestUtils;
import com.weifly.weistock.core.util.WeistockUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 新浪股票K线 V2
 *
 * @author weifly
 * @since 2021/7/3
 */
public class SinaStockKLineV2Service implements StockKLineService {

    // https://quotes.sina.cn/cn/api/jsonp.php/var%20_sz1599152019_7_29=/KC_MarketDataService.getKLineData?symbol=sz159915
    public static final String URL_STOCK_DATA_1 = "https://quotes.sina.cn/cn/api/jsonp.php/var%20_";
    public static final String URL_STOCK_DATA_2 = "=/KC_MarketDataService.getKLineData?symbol=";

    private Logger log = LoggerFactory.getLogger(SinaStockKLineV2Service.class);

    private SinaStockMarketService stockMarketService = new SinaStockMarketService();

    @Override
    public StockKLineBO loadStockKLine(String stockCode) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
        String fullUrl = URL_STOCK_DATA_1 + stockCode + sdf.format(new Date()) + URL_STOCK_DATA_2 + stockCode;
        // log.info("stock data url: " + fullUrl);
        String stockDataStr = HttpRequestUtils.sendGet(fullUrl, "GBK");
        if (stockDataStr == null) {
            return null;
        }
        int startIdx = stockDataStr.indexOf("(");
        if (startIdx == -1) {
            return null;
        }
        int endIdx = stockDataStr.indexOf(")", startIdx + 1);
        if (endIdx == -1) {
            return null;
        }
        String targetStr = stockDataStr.substring(startIdx + 1, endIdx);
        // log.info("data json : " + targetStr);
        List dayInfoList = WeistockUtils.toJsonObject(targetStr, List.class);
        if (dayInfoList == null || dayInfoList.isEmpty()) {
            return null;
        }

        // 解析day集合
        LinkedList<StockDayBO> dayList = new LinkedList<>();
        SimpleDateFormat sdfFrom = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTo = new SimpleDateFormat(DateUtils.FORMATTER_DATE);
        for (int i = 0; i < dayInfoList.size(); i++) {
            Map dayInfo = (Map) dayInfoList.get(i);
            StockDayBO dayBO = new StockDayBO();
            try {
                String day = (String) dayInfo.get("d");
                dayBO.setDay(sdfTo.format(sdfFrom.parse(day)));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            // 开盘价
            String openStr = (String) dayInfo.get("o");
            dayBO.setOpen(Double.parseDouble(openStr));
            // 最高价
            String highStr = (String) dayInfo.get("h");
            dayBO.setHigh(Double.parseDouble(highStr));
            // 最低价
            String lowStr = (String) dayInfo.get("l");
            dayBO.setLow(Double.parseDouble(lowStr));
            // 收盘价
            String closeStr = (String) dayInfo.get("c");
            dayBO.setClose(Double.parseDouble(closeStr));
            dayList.add(dayBO);
        }
        // 排除开盘价为0的记录
        while (true) {
            if (dayList.isEmpty()) {
                break;
            }
            if (dayList.getFirst().getOpen() == 0) {
                dayList.removeFirst();
            } else {
                break;
            }
        }

        StockPriceDto stockPriceDto = this.stockMarketService.getStockPriceByFullCode(stockCode);
        StockKLineBO stockKLine = StockMarketConverter.createStockKLine(stockPriceDto);
        stockKLine.getDayList().addAll(dayList);
        return stockKLine;
    }
}
